from django.http import HttpResponse
from django.shortcuts import render
from .forms import MessageBoardForm,RegisterForm,ArticleForm1
# 请求验证装饰器
from django.views.decorators.http import require_http_methods

# 1. 从服务器上获取数据一般都是GET请求
# 2. 向服务器提交数据一般都是POST请求

# 该视图只能用GET请求或者POST请求访问，如果用其他请求访问，则会报404错误
@require_http_methods(['GET', 'POST'])
def index(request):
    # 如果用GET请求，就直接返回一个页面
    if request.method == 'GET':
        form = MessageBoardForm()
        context = {'form': form}
        return render(request, 'index.html', context=context)

    # elif request.method == 'POST': # 用表单验证用户提交的数据
    else:
        form = MessageBoardForm(request.POST)
        if form.is_valid(): # 验证成功
            title = form.cleaned_data.get('title')
            content = form.cleaned_data.get('content')
            email = form.cleaned_data.get('email')
            return HttpResponse(f"{title} - {content} - {email}")
        else:  # 验证失败
            print(form.errors)
            return HttpResponse("表单验证失败")

@require_http_methods(['GET', 'POST'])
def register_view(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    else:
        form = RegisterForm(request.POST)
        if form.is_valid(): # 验证成功
            telephone = form.cleaned_data.get('telephone')
            return HttpResponse(f"{telephone} - {telephone}")
        else:
            # print(form.errors)
            print(form.errors.get_json_data())
            return HttpResponse("表单验证失败")


@require_http_methods(['GET', 'POST'])
def articles_view(request):
    if request.method == 'GET':
        return render(request, 'article.html')
    else:
        form = ArticleForm1(request.POST)
        if form.is_valid():
            title = form.cleaned_data.get('title')
            content = form.cleaned_data.get('content')
            return HttpResponse(f"{title} - {content}")
        else:
            print(form.errors)
            return HttpResponse("表单验证失败")